// Vue MQTT组合式函数
// 提供响应式的MQTT状态和事件处理

import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import mqttManager, { AppInfoResponse, WarnStatusResponse, WorkFlowStatusResponse, MQTTStatus, MQTTConfig, MQTTEventCallbacks } from '../utils/mqttManager'

export function useMQTT()
{
  // 响应式状态
  const isConnected = ref(false)
  const isAvailable = ref(false)
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const appInfo = ref<AppInfoResponse | null>(null)
  const warnStatus = ref<WarnStatusResponse | null>(null)
  const workFlowStatus = ref<WorkFlowStatusResponse | null>(null)
  const status = reactive<MQTTStatus>({
    isInitialized: false,
    isConnected: false,
    isAvailable: false
  })

  // 计算属性
  const connectionStatus = computed(() => {
    if (isLoading.value) return 'connecting'
    if (isConnected.value) return 'connected'
    if (error.value) return 'error'
    return 'disconnected'
  })

  const statusText = computed(() => {
    switch (connectionStatus.value) {
      case 'connecting': return '连接中...'
      case 'connected': return '已连接'
      case 'error': return '连接错误'
      default: return '未连接'
    }
  })

  // 事件回调
  const eventCallbacks: MQTTEventCallbacks = {
    onConnect: () => {
      console.log('MQTT连接成功')
      isConnected.value = true
      isLoading.value = false
      error.value = null
    },

    onDisconnect: () => {
      console.log('MQTT连接断开')
      isConnected.value = false
      isAvailable.value = false
      isLoading.value = false
    },

    onError: (errorMessage: string) => {
      console.error('MQTT错误:', errorMessage)
      error.value = errorMessage
      isLoading.value = false
    },

    onAppInfoUpdate: (newAppInfo: AppInfoResponse) => {
      console.log('收到应用信息更新:', newAppInfo)
      appInfo.value = newAppInfo
    },

    onWarnStatusUpdate: (newWarnStatus: WarnStatusResponse) => {
      console.log('收到警告状态更新:', newWarnStatus)
      warnStatus.value = newWarnStatus
    },

    onWorkFlowStatusUpdate: (newWorkFlowStatus: WorkFlowStatusResponse) => {
      console.log('收到工作流程状态更新:', newWorkFlowStatus)
      workFlowStatus.value = newWorkFlowStatus
    },

    onStatusChange: (newStatus: MQTTStatus) => {
      Object.assign(status, newStatus)
      isConnected.value = newStatus.isConnected
      isAvailable.value = newStatus.isAvailable
    }
  }

  // 连接方法
  const connect = async (config: MQTTConfig): Promise<boolean> => {
    if (!config) {
      error.value = '未提供MQTT配置'
      return false
    }

    try {
      isLoading.value = true
      error.value = null
      
      const result = await mqttManager.connect(config)
      
      if (result.success) {
        return true
      } else {
        error.value = result.error || '连接失败'
        return false
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '连接异常'
      return false
    }
  }

  // 断开连接
  const disconnect = async (): Promise<boolean> => {
    try {
      isLoading.value = true
      const result = await mqttManager.disconnect()
      isLoading.value = false
      return result.success
    } catch (err) {
      error.value = err instanceof Error ? err.message : '断开连接异常'
      isLoading.value = false
      return false
    }
  }

  // 重新连接
  const reconnect = async (): Promise<boolean> => {
    try {
      isLoading.value = true
      error.value = null
      const result = await mqttManager.reconnect()
      if (result.success) {
        return true
      } else {
        error.value = result.error || '重连失败'
        return false
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '重连异常'
      return false
    }
  }

  // 请求应用信息
  const requestAppInfo = async (): Promise<boolean> => {
    try {
      const result = await mqttManager.requestAppInfo()
      return result.success
    } catch (err) {
      error.value = err instanceof Error ? err.message : '请求应用信息异常'
      return false
    }
  }

  // 获取当前应用信息
  const getAppInfo = async (): Promise<AppInfoResponse | null> => {
    try {
      const info = await mqttManager.getAppInfo()
      appInfo.value = info
      return info
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取应用信息异常'
      return null
    }
  }

  // 请求警告状态数据
  const requestWarnStatus = async (): Promise<boolean> => {
    try {
      const result = await mqttManager.requestWarnStatus()
      return result.success
    } catch (err) {
      error.value = err instanceof Error ? err.message : '请求警告状态异常'
      return false
    }
  }

  // 获取当前警告状态
  const getWarnStatus = async (): Promise<WarnStatusResponse | null> => {
    try {
      const status = await mqttManager.getWarnStatus()
      warnStatus.value = status
      return status
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取警告状态异常'
      return null
    }
  }

  // 清除错误
  const clearError = (): void => {
    error.value = null
  }

  // 初始化
  const initialize = async (): Promise<void> => {
    // 设置事件回调
    mqttManager.setEventCallbacks(eventCallbacks)
  }

  // 清理
  const cleanup = (): void => {
    mqttManager.removeEventCallbacks()
  }

  // 生命周期钩子
  onMounted(() => {
    initialize()
  })

  onUnmounted(() => {
    cleanup()
  })

  return {
    // 状态
    isConnected,
    isAvailable,
    isLoading,
    error,
    appInfo,
    warnStatus,
    workFlowStatus,
    status,
    
    // 计算属性
    connectionStatus,
    statusText,
    
    // 方法
    connect,
    disconnect,
    reconnect,
    requestAppInfo,
    getAppInfo,
    requestWarnStatus,
    getWarnStatus,
    clearError,
    
    // 生命周期
    initialize,
    cleanup
  }
}

// 简化的MQTT Hook（用于只读状态）
export function useMQTTStatus() {
  const isConnected = ref(false)
  const isAvailable = ref(false)
  const status = reactive<MQTTStatus>({
    isInitialized: false,
    isConnected: false,
    isAvailable: false
  })

  const eventCallbacks: MQTTEventCallbacks = {
    onStatusChange: (newStatus: MQTTStatus) => {
      Object.assign(status, newStatus)
      isConnected.value = newStatus.isConnected
      isAvailable.value = newStatus.isAvailable
    }
  }

  onMounted(() => {
    mqttManager.setEventCallbacks(eventCallbacks)
  })

  onUnmounted(() => {
    mqttManager.removeEventCallbacks()
  })

  return {
    isConnected,
    isAvailable,
    status
  }
}
